package com.yumijinfu.mian;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cookie.store.MemoryCookieStore;
import com.lzy.okhttputils.model.HttpHeaders;
import com.tencent.bugly.crashreport.CrashReport;
import com.yumijinfu.util.Session;
import com.yumijinfu.util.SharedPreferencesSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：黑哥 on 2016/3/29 10:09
 */
public class YuMiJinFuAplication extends MultiDexApplication {
    private String TAG = this.getClass().getSimpleName();
    //得到上下文
    private static Context context;
    public static YuMiJinFuAplication mApp;
    //存储数据
    private Session session;
    //activity的集合用于添加或关闭activity
    public List<Activity> mAcitivity;

    private static final int TIME_OUT = 60000;//1分钟

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mApp = this;

        this.session = new SharedPreferencesSession(this);
        OkHttpUtils.init(this);
        OkHttpUtils
                .getInstance()
                .addCommonHeaders(getHeader())
                .debug("http")
                .setCookieStore(new MemoryCookieStore())//cookie使用内存缓存（app退出后，cookie消失）
                .setConnectTimeout(TIME_OUT)
                .setReadTimeOut(TIME_OUT)
                .setWriteTimeOut(TIME_OUT);
        ;
        /**
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
//        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
//                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {
//            /**
//             * IMKit SDK调用第一步 初始化
//             */
//            RongIM.init(this);
//        }
        /**bug检测初始化*/
         CrashReport.initCrashReport(getApplicationContext(), "c7e81598b7", false);

        //把自定义的异常处理类设置 给主线程
        MyCrashHandler myCrashHandler =    MyCrashHandler.getInstance();
        myCrashHandler.init(getApplicationContext());
        Thread.currentThread().setUncaughtExceptionHandler(myCrashHandler);


    }

    /**
     * 请求头信息
     *
     * @return
     */
    public static HttpHeaders getHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("jsessionid", YuMiJinFuAplication.mApp.getSession().get("jsessionid"));
        headers.put("fundSessionId", YuMiJinFuAplication.mApp.getSession().get("fundSessionId"));
//
        return headers;
    }

//    private void initImageLoader() {
//        DisplayImageOptions options = new DisplayImageOptions.Builder()
//                .cacheInMemory(true)    //缓存在内存
//                .cacheOnDisk(true)      //缓存至本地
////              .showImageOnFail(R.mipmap.icon_80)
//                .build();
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
//                .diskCache(new UnlimitedDiscCache(new File(Environment.getExternalStorageDirectory() + File.separator + Config.base_data_path + File.separator + Config.images_cache_path)))
//                .defaultDisplayImageOptions(options)
//                .diskCacheSize(1024 * 1024 * 100)
//                .build();
//        ImageLoader.getInstance().init(config);
//    }

    /**
     * 添加activity
     */
    public void AddActivity(Activity activity) {
        if (mAcitivity == null) {
            mAcitivity = new ArrayList<Activity>();
        }
        mAcitivity.add(activity);
    }

    /**
     * 移除activity
     */
    public void RemoveActivity() {
        if (mAcitivity != null&&mAcitivity.size()>0) {
            for (int i = 0; i < mAcitivity.size(); i++) {
                mAcitivity.get(i).finish();
            }
            mAcitivity.clear();
        }
    }

    //得到
    public Session getSession() {
        return session;
    }

    //设置
    public void setSession(Session session) {
        this.session = session;
    }

    // 存储数据比较
    public boolean sessionEqual(String key, String cVal) {
        return this.session.get(key) != null
                && this.session.get(key).equals(cVal);
    }

    @SuppressLint("NewApi")
    public boolean hasLogin() {
        if (TextUtils.isEmpty(YuMiJinFuAplication.mApp.getSession().get("jsessionid"))) {//token
            return false;
        } else {
            return true;
        }
    }

    // 退出清空session
    public void logout() {
        Map<String, String> vals = new HashMap<String, String>();
//        vals.put("TOKEN", "");
        vals.put("jsessionid", "");
       /* vals.put("avatarImg", "");
        vals.put("userPhone", "");*/
        this.session.set(vals);
//        clearUser();
//        user = null;
    }
//
//    public void fundLogout() {
//        Map<String, String> vals = new HashMap<String, String>();
//        vals.put("fundSessionId","");
//        getHeader().remove("fundSessionId");
//        this.session.set(vals);
//    }

    //清空token
    public void removeToken() {
        Map<String, String> vals = new HashMap<String, String>();
        vals.put("token", "");
        this.session.set(vals);
    }

    // 依据key value 存储数据
    public void setSessionVal(String key, String value) {
        this.session.set(key, value);
    }


    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

//    public UserInfo getUser() {
//        if (user == null) {
//            return recoverUser();
//        }
//        return user;
//    }
//
//    public void setUser(UserInfo netUser) {
//        user = netUser;
//        if (user != null) {
//            saveUser(user);
//        }
//    }
//
//    private UserInfo recoverUser() {
//        try {
//            FileInputStream fos = this.openFileInput(apiConfig.user_file_name);
//            ObjectInputStream oinput;
//            oinput = new ObjectInputStream(fos);
//            UserInfo user = (UserInfo) oinput.readObject();
//            fos.close();
//            oinput.close();
//            Log.i(TAG, "recover user success!");
//            Log.i(TAG, user.toString());
//            return user;
//        } catch (Exception e) {
//            Log.i(TAG, "recover user failed!");
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    public void saveUser(UserInfo user) {
//        try {
//            FileOutputStream fos = this.openFileOutput(apiConfig.user_file_name,
//                    Context.MODE_PRIVATE);
//            ObjectOutputStream oout = null;
//            oout = new ObjectOutputStream(fos);
//            oout.writeObject(user);
//            fos.close();
//            oout.close();
//            Log.i(TAG, "save user success!");
//        } catch (Exception e) {
//            Log.i(TAG, "save user failed!");
//            e.printStackTrace();
//        }
//    }
//
//    public void clearUser() {
//        try {
//            FileOutputStream fos = this.openFileOutput(apiConfig.user_file_name,
//                    Context.MODE_PRIVATE);
//            ObjectOutputStream oout = null;
//            oout = new ObjectOutputStream(fos);
//            oout.writeObject(null);
//            fos.close();
//            oout.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//


}
